package com.king.nio.zerocopy;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NewIoClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 7001));

        // 得到一个文件channel
        String fileName = "test.pdf";
        FileChannel fileChannel = new FileInputStream(fileName).getChannel();

        // 准备发送
        long startTime = System.currentTimeMillis();

        // 在 linux 下一个 transferTo 方法就可以完成传输
        // 在 windows 下，一次调用 transferTo 只能发送 8M, 大文件需要分段，且要注意传输时的位置
        long num = 8L * 1024 * 1024;
        long start = 0L;
        long index = Math.min(fileChannel.size(), num);

        while (index <= fileChannel.size()) {
            if(0 == fileChannel.transferTo(start, index, socketChannel)){
                break;
            }
            start = index;
            index += Math.min(fileChannel.size() - index, num);
        }

        System.out.println("发送的总字节数 = " + index + " 耗时: " + (System.currentTimeMillis() - startTime));

        // 关闭
        fileChannel.close();
        socketChannel.close();
    }
}
